package com.todod.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.todod.common.util.MinIoUtils;
import com.todod.dto.PublicFileDto;
import com.todod.entity.QueryPublicFile;
import com.todod.entity.ReqPublicFile;
import com.todod.entity.ResultData;
import com.todod.mapper.PublicCatalogMapper;
import com.todod.mapper.PublicFileMapper;
import com.todod.model.PublicCatalog;
import com.todod.model.PublicFile;
import com.todod.model.PublicFileEvaluate;
import com.todod.model.PublicFileShare;
import com.todod.model.User;
import com.todod.service.IUserService;
import com.todod.service.PublicCatalogService;
import com.todod.service.PublicFileEvaluateService;
import com.todod.service.PublicFileService;
import com.todod.service.PublicFileShareService;

/**
 * @param
 * @author dyl
 * @date 2021-03-16
 */
@RestController
@RequestMapping("/publicFile")
public class PublicFileController extends BaseManageController {
	@Autowired
	private PublicFileService publicFileService;
	@Autowired
	private PublicFileMapper publicFileMapper;
	@Autowired
	private IUserService iUserService;
	@Autowired
	public PublicFileEvaluateService publicFileEvaluateService;
	@Value("${file.visit}")
	private String visi;
	@Autowired
	private PublicFileShareService publicFileShareService;
	@Autowired
	public PublicCatalogService publicCatalogService;
	@Autowired
	public PublicCatalogMapper publicCatalogMapper;
	// 存储桶名称
	@Value("${minio.bucketName}")
	private String bucketName;
	@Autowired
	private MinIoUtils minIoUtils;

	/**
	 * 
	 * @param companyId
	 * @param _userId
	 * @param request
	 * @param queryProjectInfo
	 * @return
	 */
	@RequestMapping("/getListPage")
	public ResultData getListPage(@RequestAttribute Long _userId, HttpServletRequest request,
			@RequestBody QueryPublicFile queryPublicFile) {
		IPage<PublicFileDto> page = null;
		// 共享文件夹
		if (queryPublicFile.getShareFlag() != null && queryPublicFile.getShareFlag().equalsIgnoreCase("1")) {
			page = publicFileService.getShareListPage(_userId, queryPublicFile);
			// 个人创建文件夹
		} else {
			page = publicFileService.getListPage(_userId, queryPublicFile);
		}

		return ResultData.success("ok", page);
	}

	/**
	 * @param _userId
	 * @param queryProjectInfo
	 * @return
	 */
	@RequestMapping("/getListPageInState")
	public ResultData getListPageInState(@RequestAttribute Long _userId, @RequestBody QueryPublicFile queryPublicFile) {
		IPage<PublicFileDto> page = publicFileService.getListPageInState(_userId, queryPublicFile);
		return ResultData.success("ok", page);
	}

	/**
	 * 
	 * @param _userId
	 * @param request
	 * @param response
	 * @param xftId
	 * @param xiangmuId
	 * @param companyId
	 * @return
	 */
	@PostMapping("/uploadFile")
	public ResultData uploadFile(@RequestAttribute Long _userId, HttpServletRequest request,
			HttpServletResponse response, Long gftId, String batchCode) {
		User user = iUserService.getById(_userId);
		try {
			request.setCharacterEncoding("utf-8");

			MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
			MultipartFile uploadFile = req.getFile("uploadfile_ant");// 返回上传文件的内容和描述
			String originalName = uploadFile.getOriginalFilename();

			boolean flag = publicFileService.getFileByFileName(originalName, gftId);

			if (flag != true) {
				PublicFile publicFile = publicFileService.saveUploadFile(_userId, request, gftId, user.getDepartid(),
						batchCode);
				return ResultData.success("ok", publicFile);
			} else {
				return ResultData.error("当前上传文件数据库已存在，您可以查询之后进行修改或者修改名称后再上传");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResultData.error("error");
		}
	}

	/**
	 * 
	 * @param _userId
	 * @param reqProjectInfo
	 * @return
	 */
	@PostMapping("/save")
	public ResultData saveData(@RequestAttribute Long _userId, @RequestBody PublicFile publicFile) {

		try {
			publicFileService.saveData(_userId, publicFile);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return ResultData.error(e.toString().substring(20));
		}
		return ResultData.success();
	}

	/**
	 * 
	 * @param _userId
	 * @param reqProjectInfo
	 * @return
	 */
	@PostMapping("/edit")
	public ResultData editData(@RequestAttribute Long _userId, @RequestBody PublicFile publicFile) {

		try {
			publicFileService.editData(_userId, publicFile);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return ResultData.error(e.toString().substring(20));
		}
		return ResultData.success();
	}

	/**
	 * 
	 * @param _userId
	 * @param publicFile
	 * @return
	 */
	@PostMapping("/copy")
	public ResultData copyData(@RequestAttribute Long _userId, @RequestBody PublicFile publicFile) {

		try {
			publicFileService.copyData(_userId, publicFile);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return ResultData.error(e.toString().substring(20));
		}
		return ResultData.success();
	}

	/**
	 * 
	 * @param _userId
	 * @param publicFile
	 * @return
	 */
	@PostMapping("/move")
	public ResultData moveData(@RequestAttribute Long _userId, @RequestBody PublicFile publicFile) {

		try {
			publicFileService.moveData(_userId, publicFile);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return ResultData.error(e.toString().substring(20));
		}
		return ResultData.success();
	}

	/**
	 * 
	 * @param code
	 * @return
	 */
	@GetMapping("/getInfo")
	public ResultData getInfo(Long code) {

		if (code == null) {
			return ResultData.error(ResultData.PARAM_ERROR_CODE, "参数错误");
		}

		List<PublicFileDto> list = publicFileMapper.getInfo(code);
		for (PublicFileDto key : list) {
			key.setName(key.getOriginalName());

			User user = iUserService.getById(key.getCreateuserId());
			key.setCreateuserName(user.getNickName());

			int result01 = key.getSuffix().indexOf("docx");
			int result02 = key.getSuffix().indexOf("doc");
			int result03 = key.getSuffix().indexOf("xlsx");
			int result04 = key.getSuffix().indexOf("xls");
			int result05 = key.getSuffix().indexOf("txt");
			int result06 = key.getSuffix().indexOf("ppt");
			int result07 = key.getSuffix().indexOf("pptx");

			if (result01 != -1 || result02 != -1 || result03 != -1 || result04 != -1 || result05 != -1 || result06 != -1
					|| result07 != -1) {
				key.setUrl(key.getYulanPath());
				key.setSuffix("pdf");
			} else {
				key.setUrl(key.getAbstractPath());
				key.setSuffix(key.getSuffix());
			}
		}
		return ResultData.success("ok", list);
	}

	/**
	 * 
	 * @param code
	 * @return
	 */
	@GetMapping("/getFileInfo")
	public ResultData getFileInfo(Long code) {

		if (code == null) {
			return ResultData.error(ResultData.PARAM_ERROR_CODE, "参数错误");
		}

		ArrayList<Object> list = new ArrayList<>();
		List<PublicFileDto> keys = publicFileMapper.getInfo(code);
		for (PublicFileDto key : keys) {
//			list.add(visi + key.getRelativePath());
			list.add(key.getAbstractPath());
		}
		return ResultData.success("ok", list);
	}

	/**
	 * 
	 * @param batchCode
	 * @return
	 */
	@GetMapping("/getHistory")
	public ResultData getHistory(String batchCode) {

		List<PublicFileDto> list = publicFileMapper.getListByBatchCode(batchCode);
		for (PublicFileDto publicFile : list) {
			User user = iUserService.getById(publicFile.getCreateuserId());
			publicFile.setCreateuserName(user.getNickName());

			BigDecimal size = new BigDecimal(publicFile.getFileSize());
			BigDecimal divide1 = new BigDecimal("1024");
			BigDecimal divide2 = new BigDecimal("1024").multiply(new BigDecimal("1024"));
			BigDecimal divide3 = new BigDecimal("1024")
					.multiply(new BigDecimal("1024").multiply(new BigDecimal("1024")));
			Double d1 = size.divide(divide1, 2, BigDecimal.ROUND_HALF_UP).doubleValue();
			Double d2 = size.divide(divide2, 2, BigDecimal.ROUND_HALF_UP).doubleValue();
			Double d3 = size.divide(divide3, 2, BigDecimal.ROUND_HALF_UP).doubleValue();

			if (d1 < 1) {
				publicFile.setFileSize("1KB");
			} else if (d1 >= 1) {
				publicFile.setFileSize(d1.toString() + "KB");
			}
			if (d2 >= 1) {
				publicFile.setFileSize(d2.toString() + "MB");
			}
			if (d3 >= 1) {
				publicFile.setFileSize(d3.toString() + "GB");
			}
		}

		return ResultData.success("ok", list);
	}

	/**
	 * 
	 * @param companyId
	 * @param _userId
	 * @param request
	 * @param queryProjectInfo
	 * @return
	 */
	@RequestMapping("/getFileList")
	public ResultData getFileList(@RequestAttribute Long _userId) {
		User user = iUserService.getById(_userId);

		List<PublicFileDto> list = publicFileMapper.getFileList(_userId, user.getDepartid());
		return ResultData.success("ok", list);
	}

	/**
	 * 
	 * @param companyId
	 * @param _userId
	 * @param request
	 * @param queryProjectInfo
	 * @return
	 */
	@RequestMapping("/getSPListPage")
	public ResultData getSPListPage(@RequestAttribute Long _userId, HttpServletRequest request,
			@RequestBody QueryPublicFile queryPublicFile) {

		IPage<PublicFileDto> page = publicFileService.getSPListPage(_userId, queryPublicFile);
		return ResultData.success("ok", page);
	}

	/**
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("/delete")
	public ResultData delete(@RequestAttribute Long _userId, Long code) {

		if (code == null) {
			return ResultData.error(ResultData.PARAM_ERROR_CODE, "参数错误");
		}
		List<PublicFileEvaluate> list = publicFileEvaluateService.getEvaluateListByFileId(code);

		PublicFile publicFile = publicFileMapper.selectById(code);
		if (!_userId.equals(publicFile.getCreateuserId())) {
			return ResultData.error(ResultData.PARAM_ERROR_CODE, "不可删除非当前登录人创建的文档");
		}
		if (publicFile.getState().equalsIgnoreCase("2")) {
			return ResultData.error(ResultData.PARAM_ERROR_CODE, "不可删除审批通过的文档");
		}
		if (list != null && list.size() > 0) {
			return ResultData.error(ResultData.PARAM_ERROR_CODE, "当前文档已评价，不可删除");
		}
		publicFileMapper.deleteById(code);
		minIoUtils.removeObject(bucketName, publicFile.getFileName());
		return ResultData.success();
	}

	/**
	 * @Title: downLoad
	 * @Description: 附件下载
	 * @author lql
	 * @date 2021年3月1日
	 * @return ResponseEntity响应的头文件信息，具体信息
	 */
	@RequestMapping(value = "/downLoad", method = RequestMethod.POST, produces = "application/json")
	@ResponseBody
	public void downLoad(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") String id) {
		PublicFile publicFile = publicFileMapper.selectById(Long.valueOf(id));
		try {
			String string = publicFile.getRelativePath();
			String fileName = string.substring(string.indexOf("/") + 1);
			String originalName = publicFile.getOriginalName();

			minIoUtils.download(response, bucketName, fileName, originalName);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @param companyId
	 * @param _userId
	 * @param request
	 * @param queryProjectInfo
	 * @return
	 */
	@RequestMapping("/getNewFileList")
	public ResultData getNewFileList(@RequestAttribute Long _userId, String flag) {
		User user1 = iUserService.getById(_userId);

		List<PublicFileDto> list = null;
		List<PublicFileDto> list1 = new ArrayList<>();
		if (flag.equalsIgnoreCase("M")) {
			list = publicFileMapper.getNewFileList1(user1.getId(), user1.getDepartid());
			for (PublicFileDto publicFile : list) {
				User user = iUserService.getById(publicFile.getCreateuserId());
				publicFile.setCreateuserName(user.getNickName());

				if (!_userId.equals(publicFile.getCreateuserId())) {// 判断登录人与创建人是否一致
					publicFile.setShareFlag("0");
				} else {
					publicFile.setShareFlag("1");
				}
				list1.add(publicFile);
			}
		} else {
			list = publicFileMapper.getNewFileList2(_userId, user1.getDepartid());
			for (PublicFileDto publicFile : list) {
				User user = iUserService.getById(publicFile.getCreateuserId());
				publicFile.setCreateuserName(user.getNickName());

				if (!_userId.equals(publicFile.getCreateuserId())) {// 判断登录人与创建人是否一致
					publicFile.setShareFlag("0");
				} else {
					publicFile.setShareFlag("1");
				}
				list1.add(publicFile);
			}
		}

		return ResultData.success("ok", list1);
	}

	/**
	 * @title 获取我的文档第一层目录列表
	 * @param companyId
	 * @param _userId
	 * @param request
	 * @param queryProjectInfo
	 * @return
	 */
	@RequestMapping("/getFileShareFirst")
	public ResultData getFileShareFirst(@RequestAttribute Long _userId) {

		List<PublicFileDto> list = publicFileMapper.getFileShareFirst(_userId);// 初始化数据
		List<PublicFileDto> listShare = new ArrayList<PublicFileDto>();
		// 获取分享的文档
		List<PublicFileShare> listInAuthority = publicFileShareService.getFileAuthorityByUserId(_userId);
		if (listInAuthority != null && listInAuthority.size() > 0) {
			for (PublicFileShare publicFileShare : listInAuthority) {
				PublicCatalog publicCatalog1 = publicCatalogMapper.selectById(publicFileShare.getFileId());
				if (publicCatalog1 != null) {
					String level = publicCatalog1.getLevels();
					String[] levels = level.split(";");

					for (int i = 0; i < levels.length; i++) {
						if (i == 0) {
							PublicCatalog publicCatalog3 = publicCatalogMapper.selectById(levels[i]);

							PublicFileDto publicFile2 = new PublicFileDto();
							publicFile2.setId(publicCatalog3.getId());
							publicFile2.setGftId(publicCatalog3.getId());
							publicFile2.setSortNum(0);
							publicFile2.setOriginalName(publicCatalog3.getTypeName());
							publicFile2.setType("U");
							publicFile2.setState("1");
							publicFile2.setShareFlag("1");
							if (!list.contains(publicFile2)) {
								list.add(publicFile2);
							}
						}
					}
				}

				PublicFile publicFile = publicFileService.selectByCodeInUse(publicFileShare.getFileId());
				if (publicFile != null) {
					String level = publicFile.getLevel();
					String[] levels = level.split(";");
					PublicCatalog publicCatalog3 = publicCatalogMapper.selectById(levels[0]);

					PublicFileDto publicFile2 = new PublicFileDto();
					publicFile2.setId(publicCatalog3.getId());
					publicFile2.setGftId(publicCatalog3.getId());
					publicFile2.setSortNum(0);
					publicFile2.setOriginalName(publicCatalog3.getTypeName());
					publicFile2.setType("U");
					publicFile2.setState("1");
					publicFile2.setShareFlag("1");
					if (!list.contains(publicFile2)) {
						list.add(publicFile2);
					}
				}

			}
			list.addAll(listShare);
		}

		return ResultData.success("ok", list);
	}

	/**
	 * @title 获取我的文档第二层目录列表
	 * @param _userId
	 * @param request
	 * @param queryPublicFile
	 * @return
	 */
	@RequestMapping("/getFileSharePage")
	public ResultData getFileSharePage(@RequestAttribute Long _userId, HttpServletRequest request,
			@RequestBody QueryPublicFile queryPublicFile) {
		IPage<PublicFileDto> page = null;
		// 共享文件夹
		if (queryPublicFile.getShareFlag() != null && queryPublicFile.getShareFlag().equalsIgnoreCase("1")) {
			page = publicFileService.getFileSharePage(_userId, queryPublicFile);
			// 个人创建文件夹
		} else if (queryPublicFile.getShareFlag() != null && queryPublicFile.getShareFlag().equalsIgnoreCase("2")) { // 我的收藏
			page = publicFileService.getCollectListPage(_userId, queryPublicFile);
		} else {
			page = publicFileService.getFileShareList(_userId, queryPublicFile);
		}

		return ResultData.success("ok", page);
	}

	/**
	 * 
	 * @param _userId
	 * @param reqProjectInfo
	 * @return
	 */
	@PostMapping("/batchSave")
	public ResultData batchSave(@RequestAttribute Long _userId, @RequestBody ReqPublicFile reqPublicFile) {

		PublicFile publicFile = reqPublicFile.getData();
		List<PublicFile> list = reqPublicFile.getData1();

		try {
			publicFileService.batchSave(_userId, publicFile, list);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return ResultData.error(e.toString().substring(20));
		}
		return ResultData.success();
	}

	/**
	 * 
	 * @param companyId
	 * @param _userId
	 * @param request
	 * @param queryProjectInfo
	 * @return
	 */
	@RequestMapping("/getNewListPage")
	public ResultData getNewListPage(@RequestAttribute Long _userId, HttpServletRequest request,
			@RequestBody QueryPublicFile queryPublicFile) {
		IPage<PublicFileDto> page = publicFileService.getNewListPage(_userId, queryPublicFile);

		return ResultData.success("ok", page);
	}

	/**
	 * 
	 * @param companyId
	 * @param _userId
	 * @param request
	 * @param queryProjectInfo
	 * @return
	 */
	@RequestMapping("/getFirstPageList")
	public ResultData getFirstPageList(@RequestAttribute Long _userId, String flag) {
		User user1 = iUserService.getById(_userId);

		List<PublicFileDto> list = null;
		List<PublicFileDto> list1 = new ArrayList<>();
		list = publicFileMapper.getFirstPageList(user1.getId(), user1.getDepartid());
		for (PublicFileDto publicFile : list) {
			User user = iUserService.getById(publicFile.getCreateuserId());
			publicFile.setCreateuserName(user.getNickName());

			if (!_userId.equals(publicFile.getCreateuserId())) {// 判断登录人与创建人是否一致
				publicFile.setShareFlag("0");
			} else {
				publicFile.setShareFlag("1");
			}
			list1.add(publicFile);
		}

		return ResultData.success("ok", list1);
	}

	/**
	 * @title deleteInLogic
	 * @description 逻辑删除
	 * @param _userId
	 * @param ids
	 * @param status(-1:删除 ;1:使用)
	 * @return
	 */
	@PostMapping("/deleteInLogic")
	public ResultData deleteInLogic(@RequestAttribute Long _userId, String ids, String status) {
		String[] split = ids.split(",");
		for (String s : split) {
			Long id = Long.valueOf(s);
			try {
				publicFileService.updateUserAndStatus(_userId, id, status);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return ResultData.success();
	}

}
